package java6681.lesson13;

/**
 * @author Junichiro
 * @description 多线程同步
 * @date 2021-06-05 19:54
 **/

public class BankSynchronized6681 {
    private static BankAccount6681 account;

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        account = new BankAccount6681("6681", 1000);
        System.out.println(account.getBankID() +
                "账上开始余额" + account.getBalance() + "元");
        Thread t1 = new Thread(BankSynchronized6681::bank6681, "会计");
        Thread t2 = new Thread(BankSynchronized6681::bank6681, "出纳");
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(account.getBankID() +
                "账上最终余额" + account.getBalance() + "元");

        long endTime = System.currentTimeMillis();
        long usedTime = (endTime - startTime);
        System.out.println("用时:" + usedTime);
    }

    private static void bank6681() {
        String name = Thread.currentThread().getName();
        String action = "";
        int money = 0, b = 0;
        if (name.equals("会计")) {
            money += 300;
            action = "存入";
        } else if (name.equals("出纳")) {
            money -= 100;
            action = "取出";
        }
        synchronized (BankSynchronized6681.class) {
            for (int i = 0; i < 1; i++) {
                b = account.getBalance() + money;
                System.out.println(name + action + Math.abs(money));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                account.setBalance(b);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
